import React, {PropsWithChildren, useEffect, useState} from "react"
import ActionsDrawerLayout from "../components/ActionsDrawerLayout";
import {Form} from "antd";
import {FormInstance} from "antd/es/form/hooks/useForm";

export interface FormDrawerProps<Values> {
    open: boolean
    title: string
    onClose: () => void
    onConfirm: (values:Values)=>Promise<unknown>
    initialValues?:Values
    onBeforeConfirm?: ()=>void
    form?:FormInstance
}

function FormDrawer<Values = any>({open, title, onClose,onConfirm,children,initialValues,onBeforeConfirm,form}: PropsWithChildren<FormDrawerProps<Values>>) {
    const [loading, setLoading] = useState(false)
    let [myFrom] = Form.useForm();
    let formInstance = form??myFrom
    useEffect(() => {
        if (open ){
            formInstance.setFieldsValue(initialValues)
        }
        if (!open){
            formInstance.resetFields()
        }
    }, [open,formInstance]);
    return (
        <ActionsDrawerLayout confirmLoading={loading} onClose={()=> {
            onClose()
        }} open={open} onConfirm={()=>{
            onBeforeConfirm&&onBeforeConfirm()
            formInstance.submit()
        }} title={title}>
            <Form<Values> layout={"vertical"} form={formInstance} onFinish={values => {
                setLoading(true)
                onConfirm(values).finally(()=>{
                    setLoading(false)
                })
            }}>
                {children}
            </Form>
        </ActionsDrawerLayout>
    )
}

export default FormDrawer
